package com.h2.controller;

import com.h2.dao.UserDao;
import com.h2.dto.UserDto;
import com.h2.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.JoinType;

/**
 * @Author: TongRui乀
 * @Date: 2020-09-09 13:37
 * @description：
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserDao userDao;

    /**
     *  复查条件查询
     * @param userDto
     * @return
     */
    @PostMapping("getByPage")
    public Page<User> getByPage(UserDto userDto){

        Specification<User> specification = (Specification<User>) (root, query, builder) -> {

//            root.join("role", JoinType.LEFT);

            if(!StringUtils.isEmpty(userDto.getName())){
                query.where(builder.like(root.get("name"), "%"+userDto.getName()+"%"));
            }

            if(userDto.getAge() != null){
                query.where(builder.gt(root.get("age"), userDto.getAge()));
            }
            return null;
        };

        PageRequest page = PageRequest.of(userDto.getPage(), userDto.getSize(), Sort.by(Sort.Direction.DESC, "id"));

        return this.userDao.findAll(specification, page);
    }

}
